﻿using System.Diagnostics;

static class ListNodeExtensions
{
    public static IEnumerable<int> AsEnumerable(this ListNode listNode)
    {
        for (var current = listNode; current != null; current = current.next)
            yield return current.val;
    }
    public static ListNode? ToListNodes(this IEnumerable<int> ints)
    {
        ListNode listNode = new ListNode();
        ListNode? last = null;
        var current = listNode;
        foreach (var item in ints)
        {
            current.val = item;
            last = current;
            current = current.next = new ListNode();
        }
        if (last != null)
        {
            last.next = null;
            return listNode;
        }
        else
            return null;
    }
}

/// <summary>
/// https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
/// </summary>
public class Solution
{
    public ListNode ReverseKGroup(ListNode head, int k)
    {
        IEnumerable<int> result = Array.Empty<int>();

        for (var enumerable = head.AsEnumerable(); ; enumerable = enumerable.Skip(k))
        {
            var taken = enumerable.Take(k);
            if (taken.Count() < k)
            {
                result = result.Concat(taken);
                break;
            }
            else
                result = result.Concat(taken.Reverse());
        }

        var r = result.ToListNodes();
        Debug.Assert(r is not null);
        return r;
    }
}